package org.itboys.mobile.service.mongo.web.member;

import org.apache.commons.lang.StringUtils;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.coo.conmon.Finals;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mysql.wallet.CooWallet;
import org.itboys.mobile.service.mysql.weixin.wallet.CooWeixinWalletService;
import org.itboys.mobile.util.NickNameUtil;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 作者：zzq
 * 时间：2017/12/4
 * 描述：用户
 */
@Service
public class SundayMemberService extends BaseMongoService<SundayMember>{
    @Resource(name="mdlDs")
    private MongoDataSource mongoDataSource;
    @Autowired
    private CooWeixinWalletService walletService;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return mongoDataSource;
    }
    @Override
    protected Class<SundayMember> getEntityClass() {
        return SundayMember.class;
    }

    public void saveMember(SundayMember member){

        if(member.getId()==0l){
       /*     checkMemberIsExist(member.getUserName());
            member.setPassword(StringUtils.isNotEmpty(member.getPassword())? Digests.md5(member.getPassword()):Digests.md5(Finals.DEFAULT_PASSWORD));
            member.setImage(StringUtils.isNotEmpty(member.getImage())?member.getImage(): NickNameUtil.getRandomLogo());
            member.setRecommendId(-1l);
            super.save(member);
            if(LongUtil.isZreo(member.getId())){
                throw new ErrorException("系统错误");
            }
            member.setManagerPath("/"+member.getId());
            member.setSalesPath("/"+member.getId());
            super.updateExceptEmpty(member.getId(),member);
            //生成钱包
            walletService.findByMemberId(member.getId());*/

        }else{
            SundayMember oldMember=super.getById(member.getId());
            checkMemberIsExist(member.getUserName());
            member.setRecommendId(-1l);
            member.setIsSuper(1);
            member.setManagerPath("/"+member.getId());
            member.setSalesPath("/"+member.getId());
            member.setPassword(StringUtils.isNotEmpty(member.getPassword())? Digests.md5(member.getPassword()):Digests.md5(Finals.DEFAULT_PASSWORD));
            System.out.println("推荐人id=============="+member.getRecommendId());
            super.updateExceptEmpty(member.getId(), member);
        }
    }

    /**
     * 查询
     * @param request
     * @return
     */
        public PageResult<SundayMember> selectMember(HttpServletRequest request){
            Map<String,Object> param= ParamUtil.packageMongoExactParam(request,"memberLevel");
            param.put("isDeleted",Finals.NO);
            Map<String,String> containsparam =ParamUtil.packageMongoVagueParam(request,"nickName","userName");
            return super.containpageQuery(request,containsparam,param);

        }

    public PageResult<SundayMember> selectManagerMember(HttpServletRequest request,Long memberId){
        SundayMember member=super.getById(memberId);
        Long recommendId=member.getRecommendId();
        //通过推荐人的id  再加上/业绩链包括推荐人id的所有用户  模糊查询可能会会分配的用户
        String managerPath="/"+recommendId+"/";

        Map<String,Object> param= ParamUtil.packageMongoExactParam(request);
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("id !=", memberId);
        Map<String,String> containsparam =ParamUtil.packageMongoVagueParam(request,"managerPath");
        containsparam.put("managerPath",managerPath);
        return super.containMemberQuery(request,containsparam,param);
    }

    /**
     * 更换管理人
     * @param memberId
     * @param managerId
     */
    public void updateManager(Long memberId,Long managerId){
        SundayMember member=super.getById(memberId);

        SundayMember newManager=super.getById(managerId);
        if(memberId.longValue()==managerId.longValue()){
            throw new ErrorException("不能选择当前用户");
        }
        //表示已经更改过链条   只允许更改一次
        member.setIsChange(SundayCommonConstants.YES);
        //继承推荐人的管理链 并且加上自己的id
        String managerPath = StringUtils.isNotEmpty(newManager.getManagerPath())?newManager.getManagerPath()+"/"+member.getId():String.valueOf(member.getId());
        member.setManagerPath(managerPath);
        //自己新管理人的下级链
        String firstPath= StringUtils.isNotEmpty(newManager.getFirstPath())?
                newManager.getFirstPath()+"/"+member.getId():
                String.valueOf(member.getId());
        newManager.setFirstPath(firstPath);

        //更换钱包的管理人Id
        CooWallet wallet=walletService.findByMemberId(memberId);
        //去除原管理人的下级链中  当前用户的id
        SundayMember oldManager=super.getById(wallet.getManagerId());
        List<String> oldFirstPath=Arrays.asList(oldManager.getFirstPath().split("/"));
        String  newFirstPath="";
        if(ListUtil.isNotNull(oldFirstPath)){
            for(String firstId:oldFirstPath){
                if(Long.valueOf(firstId).longValue()!=memberId.longValue()){
                    newFirstPath= StringUtils.isNotEmpty(newFirstPath)?newFirstPath+"/"+firstId:firstId;
                }
            }
        }
        oldManager.setFirstPath(newFirstPath);
        wallet.setManagerId(managerId);
        walletService.update(wallet);
        super.updateExceptEmpty(oldManager.getId(),oldManager);
        super.updateExceptEmpty(member.getId(),member);
        super.updateExceptEmpty(newManager.getId(),newManager);

    }
    /**
     * 查找单个
      * @param memberId
     * @return
     */
    public SundayMember findOne(Long memberId){
        SundayMember member=null;
        if(LongUtil.isNotZreo(memberId)){
            member=super.getById(memberId);

        }else {
            member=new SundayMember();
        }
        return member;
    }


    /**
     * 重置密码
     * @param memberId
     */
    public void resetPassword(Long memberId){
        super.update(memberId, "password", Digests.md5(Finals.DEFAULT_PASSWORD));
    }

    /**
     * 删除
     * @param memberId
     */
    public void deleteMember(Long memberId){
        super.delete(memberId);
        logger.info("删除用户","id="+memberId);
    }
    /**
     * 检测用户是否注册
     * @param userName
     */
    public void checkMemberIsExist(String userName){
        Map<String,Object> param = new HashMap<String, Object>();
        param.clear();
        param.put("userName", userName);
        param.put("isDeleted", SundayCommonConstants.NO);
        if(ListUtil.isNotNull(super.list(param))){
            throw new ErrorException("该手机号已经注册");
        }



    }
}
